package com.xindaoapp.happypet.viewpager.windows;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Fans;
import com.xindaoapp.happypet.bean.Fans.Fan;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;
import com.xindaoapp.happypet.viewpager.ViewPagerWindow;

/**
 * 用户关注
 * 
 * @author chenghao
 * 
 */
public class UserMyAttentionWindow extends ViewPagerWindow {
    private final String uid;
    private PullToRefreshListView listView;
    private View mView;

    public UserMyAttentionWindow(Activity context, String uid) {
        super(context);
        this.uid = uid;
    }

    @Override
    protected View onCreateView() {
        mView = View.inflate(mContext, R.layout.fragment_other_tab3, null);
        return View.inflate(mContext, R.layout.fragment_other_tab3, null);
    }

    @Override
    protected void initViews() {
        super.initViews();
        initUi(getView());
    }

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        initAttention(page);
    }

    protected void initUi(View view) {
        listView = (PullToRefreshListView) view.findViewById(R.id.listview);
        listView.setPullRefreshEnabled(true);
        listView.setScrollLoadEnabled(true);

        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                fans.clear();
                page = 1;
                initAttention(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (total == fans.size()) {
                    onLoad();
                    Toast.makeText(mContext, "没有更多了", Toast.LENGTH_SHORT).show();
                } else {
                    page++;
                    initAttention(page);
                }
            }
        });

        listView.setOnScrollListener(new OnScrollListener() {
            int state;
            boolean is = false;

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                // TODO Auto-generated method stub
                state = arg1;

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                // TODO Auto-generated method stub
                if (firstVisibleItem >= 3) {
                    is = true;
                } else {
                    is = false;
                }

                if (is) {

                    Intent intent = new Intent(Constants.SCROLL_FOR);
                    intent.putExtra("go", "up");
                    intent.putExtra("from", "2");
                    getBaseContext().sendBroadcast(intent);
                    // mView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                    // LayoutParams.WRAP_CONTENT));
                    // listView.setLayoutParams(new RelativeLayout.LayoutParams(
                    // LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

                } else {
                    Intent intent = new Intent(Constants.SCROLL_FOR);
                    intent.putExtra("go", "down");
                    intent.putExtra("from", "2");
                    getBaseContext().sendBroadcast(intent);
                    // mView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                    // LayoutParams.MATCH_PARENT));
                    // listView.setLayoutParams(new RelativeLayout.LayoutParams(
                    // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                }

                // Intent intent = new Intent(Constants.SCROLL_FOR);
                // if (firstVisibleItem >= 3) {
                // intent.putExtra("is", "up");
                // getBaseContext().sendBroadcast(intent);
                // }
            }
        });

        listView.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, MainActivity.class);
                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        UserInfoFragment.class.getCanonicalName());
                Bundle bundle = new Bundle();
                bundle.putString(Constants.KEY_UID, fans.get(position).followuid);
                bundle.putString(Constants.KEY_USERNAME, fans.get(position).fusername);
                bundle.putString(Constants.KEY_USERFACE, fans.get(position).userface);
                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                mContext.startActivity(intent);
            }
        });
    }

    private int total;
    private final List<Fan> fans = new ArrayList<Fan>();
    private Adapter adapter;

    private void initAttention(int page2) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page2));
        params.put("uid", uid);
        params.put("pagesize", "15");
        AddClient.get(Address.FANSGUANZHU, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                Fans parse = JSON.parseObject(content, Fans.class);
                if (parse.getResult().equals("0")) {
                    if (Integer.parseInt(parse.getTotal()) == 0) {
                        onNoDataArrived();
                        listView.setVisibility(View.GONE);
                        return;
                    } else {
                        List<Fan> array = parse.array;
                        if (array.size() > 0) {
                            fans.addAll(array);
                        }
                        if (adapter == null) {
                            adapter = new Adapter(fans);
                            listView.getRefreshableView().setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        if (Integer.parseInt(parse.getTotal()) < 10) {
                            listView.setPullRefreshEnabled(false);
                            listView.setScrollLoadEnabled(false);
                        }
                        total = Integer.parseInt(parse.getTotal());
                    }
                }
                onDataArrived(true);
                onLoad();
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoad();
                super.onFailure(error, content);
            }
        });
    }

    private void onLoad() {
        listView.onPullDownRefreshComplete();
        listView.onPullUpRefreshComplete();
    }

    private class Adapter extends BaseAdapter {
        private final List<Fan> fan;

        public Adapter(List<Fan> fan) {
            super();
            this.fan = fan;
        }

        @Override
        public int getCount() {
            return fan.size();
        }

        @Override
        public Object getItem(int position) {
            return fan.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.fans_list_item1, null);
                holder.face = (CircleImageView) convertView.findViewById(R.id.face);
                holder.iv_guanzhu = (ImageView) convertView.findViewById(R.id.iv_guanzhu);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(fan.get(position).userface, holder.face);
            holder.name.setText(fan.get(position).fusername);
            return convertView;
        }

    }
    class ViewHolder {
        CircleImageView face;
        ImageView iv_guanzhu;
        TextView name;
    }

    private int page = 1;
}
